/*
 * MinIO Cloud Storage (C) 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react"
import axios from "axios"
import BrowserDropdown from "./BrowserDropdown"
import Alert from "../alert/Alert"
import { connect } from "react-redux"
import web from "../web"
import * as actionsAlert from "../alert/actions"
import { minioBrowserPrefix } from "../constants"
import history from "../history"
import logo from "../../img/logo.png"
import storage from 'local-storage-fallback'

// export class TopBar extends React.Component {constructor(props) {
class TopBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showAboutModal: false,
      showChangePasswordModal: false,
      showFilePage: true,
    };
    this.toFile = this.toFile.bind(this)
  }
  componentDidMount() {
    const { showAlert, clearAlert } = this.props
    if(!web.LoggedIn()){
      web.Logout()
      history.replace("/login")
    }
    if(history.location.pathname == "/FilePage" || history.location.pathname == "/FileList"){
      this.setState({
        showFilePage: false
      })
    }else{
      this.setState({
        showFilePage: true
      })
    }
  }
  toswitch(e) {
    e.preventDefault()
    history.replace("/SwitchPage")
  }
  toFile() {
    web.RedisACLSetUser({
      username: storage.getItem('uname'),
      password: storage.getItem('pwd')
    }).then(res => {
      const { showAlert, clearAlert } = this.props
      let message = ""
      if(res.message == "OK" || res.message =="user is exists"){
        message = res.message
        console.log(message)
        showAlert("info", res.message)
        axios({
          method: 'post',
          url: "http://"+window.location.hostname+":1323/status",
          headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin':'*'},
          data: {
            addr: storage.getItem('addr'),
          }
        })
        .then(
          (response)=>{
            const { showAlert, clearAlert } = this.props
            let message = ""
            // if (response.data == "key does not exist"){
            if (response.data.toString().indexOf('load setting') !== -1){
              storage.setItem("canmount",false)
              console.log(storage.getItem("canmount") + "=====canmount TopBar")
              history.replace("/FilePage")
              message = response.data
              showAlert("info", message)
            }else {
              if(response.data.Name != ""){
                storage.setItem("canmount",true)
                history.replace("/FileList")
              }else{
                storage.setItem("canmount",false)
                history.replace("/FilePage")
              }
            }
          }
          )
          .catch(e => {
              const { showAlert, clearAlert } = this.props
          showAlert("danger", e.message)
          console.log(e.message)
            })
          }
        }).catch(e => {
          const { showAlert, clearAlert } = this.props
          showAlert("danger", e.message)
          console.log(e.message)
    })
  }
  toobject(e) {
    e.preventDefault()
    history.replace("/")
  }
  render() {
    const loggedIn = web.LoggedIn()
    const { clearAlert, alert } = this.props
    // let alertBox = <Alert {...alert} onDismiss={clearAlert} />
    // if (!alert.message) alertBox = ""
    return (
      <header className="top-header">
        <img src={logo} alt="" className="top-img"/>
        <div className="top-bottom"></div>
        <a className="top-actions" target="_blank" onClick={this.toswitch}>
          <i className="fas fa-home" />
          &nbsp;&nbsp;&nbsp;主页
        </a>
        {this.state.showFilePage ? (
        <a className="top-actions" onClick={this.toFile}>
          <i className="fas fa-folder" />
          &nbsp;&nbsp;&nbsp;文件存储
        </a>
        ):(
        <a className="top-actions" onClick={() => {
          history.replace("/")
        }}>
          <i className="fas fa-hdd" />
          &nbsp;&nbsp;&nbsp;对象存储
        </a>
        )}
        <ul className="feh-actions">
          {loggedIn ? (
            <BrowserDropdown />
          ) : (
            <a className="btn btn-danger" href={minioBrowserPrefix + "/login"}>
              登录
            </a>
          )}
        </ul>
      </header>
    )
  }
}

const mapDispatchToProps = dispatch => {
  return {
    showAlert: (type, message) =>
      dispatch(actionsAlert.set({ type: type, message: message })),
    clearAlert: () => dispatch(actionsAlert.clear())
  }
}

export default connect(
  state => state,
  mapDispatchToProps
)(TopBar)

// export default TopBar
